//
//  UITextView+Emoticon.swift
//  02-表情键盘
//
//  Created by  NorthCity on 15/11/15.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit

extension UITextView{
    
    
//    完成文本属性
    var emoticonText:String{
        var strM = String()
        let attrText = attributedText
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length ), options: []) { (dict, range, _) -> Void in
            print("-------")
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                strM += attachment.chs ?? ""
            }else{
                strM += (attrText.string as NSString).substringWithRange(range)
            }
        }
        return strM
    }
        
//    插入图片方法
    func insertEmoticon(em:Emoticon){
        //       1 空白
        if em.isEmpty {
            return
        }
        //       2 删除
        if em.isRemoved{
            deleteBackward()
            return
        }
        //       3 emoji
        if let emoji = em.emoji{
            print(selectedTextRange)
            print(selectedRange)
            replaceRange(selectedTextRange!, withText: emoji)
            return
        }
        
        //      4 图片表情
        //      文本中插入图片
        let imageText = EmoticonAttachment.imageText(em, font:font!)
        //        2> 获取文本内容
        let textM = NSMutableAttributedString(attributedString: attributedText)
        //        3> 拼接字符串
        textM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        //        4> 替换
        //            1)记录光标位置
        let range = selectedRange
        //            2) 替换文本
        attributedText = textM
        //            3) 还原光标位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
        //    5 调用代理方法
         delegate?.textViewDidChange?(self)
}
}